# 作者：陈睿-cruise
# 2025年02月19日13时21分34秒
# 2979386061@qq.com
###第一种方式——daemon设置守护进程
import multiprocessing
import os
import time

def worker():
    print(f"Worker started (PID: {os.getpid()})")
    time.sleep(5)  # 模拟子进程运行一段时间
    print(f"Worker finished (PID: {os.getpid()})")

if __name__ == "__main__":
    print(f"Main process started (PID: {os.getpid()})")

    # 创建守护进程
    process = multiprocessing.Process(target=worker)
    process.daemon = True  # 设置为守护进程

    process.start()

    print(f"Main process finished (PID: {os.getpid()})")
    # 主进程结束时，守护进程会被强制终止


###第二种方式——使用terminate
import multiprocessing
import os
import time

def worker():
    print(f"Worker started (PID: {os.getpid()})")
    while True:
        time.sleep(1)  # 模拟一个长时间运行的进程

if __name__ == "__main__":
    print(f"Main process started (PID: {os.getpid()})")

    # 创建非守护进程
    process = multiprocessing.Process(target=worker)

    process.start()

    # 模拟主进程执行一段时间
    time.sleep(2)

    # 主进程结束前显式终止子进程
    process.terminate()

    print(f"Main process finished (PID: {os.getpid()})")
    process.join()  # 等待子进程清理
